<?php
/**
 * @Author: Zhaojun(13040@qq.com)
 * @Date:   2018-04-24 16:40:00
 * @Last Modified by:   lianlianzan
 * @Last Modified time: 2021-03-19 14:25:59
 */

namespace app\actstar_manage\controller;
use app\common\controller\ManageBase;

class Signup extends ManageBase {

	function initialize() {
		parent::initialize();
		$this->saveAndGetConfigIdentify(model('Config'), '报名记录管理', '', 'signup');

		$this->activeDao = model('Active');
		$this->signupDao = model('Signup');
	}

	public function index() {
		//获取列表
		list($map, $parameter) = $this->getMap();
		$count = $this->signupDao->countSearch($map);
		$Page = new \org\util\PageBootstrap($count, config('PER_PAGE'), $parameter);
		$pageShow = $Page->show();
		list($list) = $this->signupDao->search($map, $Page->getLimit());
		//print_r($list);exit;
		$this->assign('count', $count);
		$this->assign('pageShow', $pageShow);
		$this->assign('list', $list);

		if ($parameter['kid']) {
			//获取活动信息
			$activeInfo = $this->activeDao->getInfo($parameter['kid']);
			
			//该活动总记录数
			$activeRecordNum = $this->signupDao->countSearch(['kid'=>$parameter['kid']]);
			
			//该活动总支付人数
			$activeRecordNum = $this->signupDao->countSearch(['kid'=>$parameter['kid'], 'pay_status'=>2]);
			
			//该活动总支付金额
			$activeSumAmount = $this->signupDao->baseSumSearch(['kid'=>$parameter['kid'], 'pay_status'=>2]);
		} else {
			$activeInfo = array();
			$activeRecordNum = $activeRecordNum = 0;
			$activeSumAmount = 0.00;
		}
		$this->assign('activeInfo', $activeInfo);
		$this->assign('activeRecordNum', $activeRecordNum);
		$this->assign('activeRecordNum', $activeRecordNum);
		$this->assign('activeSumAmount', $activeSumAmount);

		//获取奖品信息
		$prizeDao = model('Lotteryprize');
		list($prizeList) = $prizeDao->search(['kid'=>$parameter['kid']], '');
		$this->assign('prizeList', $prizeList);
		
		return $this->fetch();
	}

	private function getMap() {
		$map = $parameter = array();
		list($map, $parameter) = $this->getMapForUser($map, $parameter); //通用搜索

		$kid = input('param.kid', '', '', 'intval');
		if ($kid) {
			$map[] = ['kid', '=', $kid];
			$parameter['kid'] = $kid;
		}
		$this->assign('kid', $kid);

		$meid = input('param.meid', '', '', 'intval');
		if ($meid) {
			$map[] = ['meid', '=', $meid];
			$parameter['meid'] = $meid;
		}
		$this->assign('meid', $meid);
		
		$order_no = input('param.order_no', '', '', 'pwEscape');
		if ($order_no) {
			$map[] = ['order_no', 'like', '%'.$order_no.'%'];
			$parameter['order_no'] = $order_no;
		}
		$this->assign('order_no', $order_no);

		$payment_trade_no = input('param.payment_trade_no', '', 'pwEscape');
		if ($payment_trade_no) {
			$map[] = ['payment_trade_no', 'like', '%'.$payment_trade_no.'%'];
			$parameter['payment_trade_no'] = $payment_trade_no;
		}
		$this->assign('payment_trade_no', $payment_trade_no);

		$location_address = input('param.location_address', '', 'pwEscape');
		if ($location_address) {
			$map[] = ['location_address', 'like', '%'.$location_address.'%'];
			$parameter['location_address'] = $location_address;
		}
		$this->assign('location_address', $location_address);

		$location_city = input('param.location_city', '', 'pwEscape');
		if ($location_city) {
			$map[] = ['location_city', 'like', '%'.$location_city.'%'];
			$parameter['location_city'] = $location_city;
		}
		$this->assign('location_city', $location_city);

		$draw_status = input("param.draw_status", '', 'intval');
		if ($draw_status) {
			$map[] = ['draw_status', '=', $draw_status];
			$parameter['draw_status'] = $draw_status;
		}
		$this->assign('draw_status', $draw_status);

		$writeoff_status = input("param.writeoff_status", '', '', 'intval');
		if ($writeoff_status) {
			$map[] = ['writeoff_status', '=', $writeoff_status];
			$parameter['writeoff_status'] = $writeoff_status;
		}
		$this->assign('writeoff_status', $writeoff_status);

		$this->assign('parameter', $parameter);
		return array($map, $parameter);
	}

	public function add() {
		$id = input('param.id', '', 'intval');

		if ($id) {
			$info = $this->signupDao->getInfo($id);
			$kid = $info['kid'];
		} else {
			$kid = input('param.kid', '', 'intval');
		}
		$this->assign('kid', $kid);
		$this->assign('id', $id);
		$this->assign('info', $info);

		//获取活动信息
		$activeInfo = $this->activeDao->getInfo($parameter['kid']);
		$this->assign('activeInfo', $activeInfo);
		
		return $this->fetch();
	}

	public function doAdd() {
		$id = input('post.id', '', '', 'intval');
		$data = input('post.data/a', '', '', 'pwEscape');

		if ($id) {
			$info = $this->signupDao->get($id);
			$kid = $info['kid'];
		} else {
			$kid = input('post.kid', '', 'intval');
		}

		if ($id) {
			$result = $this->signupDao->baseUpdateData($id, $data);
			if ($result !== false) {
				$this->success('保存成功', url('actstar_manage/signup/index', ['kid'=>$kid]));
			} else {
				$this->error('保存失败'.showDbError($this->signupDao));
			}
		} else {
			$data['kid'] = $kid;
			$data['del_status'] = 1;
			$data['writeoff_status'] = 1;
			$data['create_time'] = $this->ts;
			$result = $this->signupDao->baseAddData($data);
			if ($result !== false) {
				$this->success('添加成功', url('actstar_manage/signup/index', ['kid'=>$kid]));
			} else {
				$this->error('添加失败'.showDbError($this->signupDao));
			}
		}
	}
	
	public function doDelete() {
		$id = input('param.id', '', '', 'intval');
		if (!$id) {
			$this->error('非法报名记录ID');
		}
		//获取报名记录信息
		$info = $this->signupDao->get($id);
		$kid = $info['kid'];

		$result = $this->signupDao->delInfo($id);
		if ($result !== false) {
			$this->success('删除成功', url('actstar_manage/signup/index', ['kid'=>$kid]));
		} else {
			$this->error('删除失败'.showDbError($this->signupDao));
		}
	}

	public function doSetWriteoff() {
		$id = input('param.id', '', 'intval');

		//获取报名记录信息
		$recordInfo = $this->signupDao->getInfo($id);

		if ($recordInfo['writeoff_status'] == 2) {
			$this->error('该报名记录已核销');
		}

		//获取活动信息
		$activeInfo = $this->activeDao->getInfo($recordInfo['kid']);

		if ($recordInfo['draw_status'] == 1) {
			$this->dealAmoutPrize($activeInfo, $recordInfo);
		} else {
			$this->error('尚未中奖，无法核销');
		}
	}

	function dealAmoutPrize($activeInfo, $recordInfo) {
		//获取微信公众号信息
		$weixinAccountDao = model('weixin_manage/WeixinAccount');
		$wxdb = $weixinAccountDao->getInfo($activeInfo['authorize_wid']);
		if (!$wxdb) {
			$this->error('微信公众号信息不存在');
		}
		//支付账号初始化
		define('WXDB_APPID', $wxdb['appid']);
		define('WXDB_MCHID', $wxdb['mchid']);
		define('WXDB_MCHKEY', $wxdb['mchkey']);
		define('WXDB_APPSECRET', $wxdb['appsecret']);
		define('WXDB_SSLCERT_PATH', EXTEND_PATH.'/weixin/'.$wxdb['wxnumber'].'/apiclient_cert.pem');
		define('WXDB_SSLKEY_PATH', EXTEND_PATH.'/weixin/'.$wxdb['wxnumber'].'/apiclient_key.pem');

		$cashMoney = $recordInfo['cash_money'];
		$amount = $cashMoney * 100;
		$orderNo = $this->_build_order_no($recordInfo['uid']);
		$openid = $recordInfo['openid'];
		$title = $activeInfo['title'];
		//获取ip
		$request = request();
		$ipaddr = $request->ip();

		if ($recordInfo['id']) {
			//企业付款
			require_once EXTEND_PATH."weixin_pay/mch_pay/WxMchPay.php";
			require_once EXTEND_PATH."weixin_pay/mch_pay/WxMchPay.Data.transfers.php";

			//②、统一下单
			$input = new \WxPayTransfers();
			$input->SetOpenid($openid); //用户openid
			$input->SetTradeNo($orderNo); //商户订单号
			$input->SetCheckName('NO_CHECK'); //校验用户姓名选项
			$input->SetAmount($amount); //企业付款金额  单位为分
			$input->SetDesc($title); //企业付款描述信息
			$input->SetSpbill_create_ip($ipaddr); //调用接口的机器IP地址

			$order = \WxMchPay::transfers($input);

			if ($order['result_code'] == 'FAIL') {
				$this->error('提示：'.$order['err_code_des'].'('.$order['err_code'].')', '', $retResult);
			} else {
				//记录状态更新
				$data = array(
					'order_no'				=> $orderNo,
					'pay_time'              => $this->ts,
					'partner_trade_no'      => $order['partner_trade_no'], //商户订单号，需保持唯一性
					'payment_trade_no'      => $order['payment_no'], //企业付款成功，返回的微信订单号
					'payment_notify_time'   => $order['payment_time'], //企业付款成功时间
					'pay_status'            => 2, //支付状态
					'writeoff_status'		=> 2, //核销状态
					'writeoff_uid'			=> $this->adminuid,
					'writeoff_username'		=> $this->adminname,
					'writeoff_time'			=> $this->ts
				);
				$this->signupDao->baseUpdateData($recordInfo['id'], $data);

				$this->success('恭喜您获得'.$cashMoney.'元，现金已转至您的微信钱包，请注意查收', '');
			}
		} else {
			$this->error('很抱歉您没中奖，请再接再厉');
		}
	}

	public function doSetWriteoffMultiple() {
		list($code, $msg, $data) = postMultiParam();
		if ($code == 0) {
			$this->error($msg);
		} else {
			$ids = $data['ids'];
		}

		//获取报名记录信息
		list($recordList) = $this->signupDao->getListByIds($ids);
		//print_r($recordList);exit;

		if ($recordInfo['writeoff_status'] == 2) {
			//$this->error('该记录奖品已发放');
		}
		//echo 1;exit;

		$kid = input('param.kid', '', '', 'intval');

		//获取活动信息
		$activeInfo = $this->activeDao->getInfo($kid);

		$this->dealAmoutPrizeMultiple($activeInfo, $recordList);
	}

	function dealAmoutPrizeMultiple($activeInfo, $recordList) {
		//获取微信公众号信息
		$weixinAccountDao = model('weixin_manage/WeixinAccount');
		$wxdb = $weixinAccountDao->getInfo($activeInfo['authorize_wid']);
		if (!$wxdb) {
			$this->error('微信公众号信息不存在');
		}
		//支付账号初始化
		define('WXDB_APPID', $wxdb['appid']);
		define('WXDB_MCHID', $wxdb['mchid']);
		define('WXDB_MCHKEY', $wxdb['mchkey']);
		define('WXDB_APPSECRET', $wxdb['appsecret']);
		define('WXDB_SSLCERT_PATH', EXTEND_PATH.'/weixin/'.$wxdb['wxnumber'].'/apiclient_cert.pem');
		define('WXDB_SSLKEY_PATH', EXTEND_PATH.'/weixin/'.$wxdb['wxnumber'].'/apiclient_key.pem');

		//获取ip
		$request = request();
		$ipaddr = $request->ip();

		$successNum = $failNum = $invalidNum = 0;
		$totalAmount = 0;
		$errorMsg = '';
		foreach ($recordList as $key => $value) {
			if ($value['draw_status'] == 1 && $value['writeoff_status'] == 1) {
				$cashMoney = $value['cash_money'];
				$amount = $cashMoney * 100;
				$orderNo = $this->_build_order_no($value['uid']);
				$openid = $value['openid'];
				$title = $activeInfo['title'];

				//企业付款
				require_once EXTEND_PATH."weixin_pay/mch_pay/WxMchPay.php";
				require_once EXTEND_PATH."weixin_pay/mch_pay/WxMchPay.Data.transfers.php";

				//②、统一下单
				$input = new \WxPayTransfers();
				$input->SetOpenid($openid); //用户openid
				$input->SetTradeNo($orderNo); //商户订单号
				$input->SetCheckName('NO_CHECK'); //校验用户姓名选项
				$input->SetAmount($amount); //企业付款金额  单位为分
				$input->SetDesc($title); //企业付款描述信息
				$input->SetSpbill_create_ip($ipaddr); //调用接口的机器IP地址

				$order = \WxMchPay::transfers($input);

				if ($order['result_code'] == 'FAIL') {
					$failNum++;
					$errorMsg = $order['err_code_des'].'('.$order['err_code'].')';
					//$this->error('提示：'.$order['err_code_des'].'('.$order['err_code'].')', '', $retResult);
				} else {
					//报名记录状态更新
					$data = array(
						'order_no'				=> $orderNo,
						'pay_time'              => $this->ts,
						'partner_trade_no'      => $order['partner_trade_no'], //商户订单号，需保持唯一性
						'payment_trade_no'      => $order['payment_no'], //企业付款成功，返回的微信订单号
						'payment_notify_time'   => $order['payment_time'], //企业付款成功时间
						'pay_status'            => 2, //支付状态
						'writeoff_status'		=> 2, //核销状态
						'writeoff_uid'			=> $this->adminuid,
						'writeoff_username'		=> $this->adminname,
						'writeoff_time'			=> $this->ts
					);
					$this->signupDao->baseUpdateData($value['id'], $data);
					$successNum++;
					$totalAmount += $cashMoney;
				}
			} else {
				$invalidNum++;
			}
		}
		$this->success('共计发放成功'.$successNum.'条数据，发放金额'.$totalAmount.'，共计发放失败'.$failNum.'条数据，共计发放失效'.$invalidNum.'条数据，请手动刷新以查看结果！'.'其中发送失败的原因是：'.$errorMsg, '');
	}

	private function _build_order_no($uid) {
		return "CM".date('YmdHis') . str_pad($uid, 8, "0", STR_PAD_LEFT) . rand(10000, 99999);
	}

	public function setCheat() {
		$signupId = input('param.signupId', '', 'intval');
		//获取报名信息
		$signupInfo = $this->signupDao->getInfo($signupId);
		$this->assign("signupId", $signupId);
		$this->assign("signupInfo", $signupInfo);
		
		//获取奖品信息
		$prizeDao = model('Lotteryprize');
		list($prizeList) = $prizeDao->search(['kid'=>$signupInfo['kid']], '');
		$prizeListDefault = [['id'=>0, 'prize_name'=>'无']];
		$prizeList = $prizeListDefault + $prizeList;
		$this->assign("prizeList", $prizeList);

		echo $this->fetch()->getContent();
	}

	public function doSetCheat() {
		$signupId = input('post.signupId', '', 'intval');
		$cheat_prize_id = input('post.cheat_prize_id', '', 'intval');

		//获取报名信息
		$signupInfo = $this->signupDao->getInfo($signupId);
		$this->assign("signupId", $signupId);
		$this->assign("signupInfo", $signupInfo);
		
		if (!$signupInfo) {
			$this->error('非法报名信息ID');
		}
		
		$data = [
			'cheat_prize_id' => $cheat_prize_id
		];
		$this->signupDao->baseUpdateData($signupId, $data);
		
		$this->success('设置奖品作弊成功');
	}
	
	public function doExcel() {
		//获取列表
		list($map, $parameter) = $this->getMap();

		//获取活动信息
		$activeInfo = $this->activeDao->getInfo($parameter['kid']);

		//获取报名记录列表
		list($signupList) = $this->signupDao->search($map, '');
		//print_r($signupList);exit;

		require_once EXTEND_PATH."org/PHPExcel/PHPExcel.php";

		// Create new PHPExcel object
		$objPHPExcel = new \PHPExcel();

		// Set document properties
		$objPHPExcel->getProperties()->setCreator("Zhaojun")
									 ->setLastModifiedBy("Maarten Balliauw")
									 ->setTitle("Office 2007 XLSX Test Document")
									 ->setSubject("Office 2007 XLSX Test Document")
									 ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
									 ->setKeywords("office 2007 openxml php")
									 ->setCategory("Test result file");

		$filename = '报名记录导出';
		$colArr = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U');
		$widArr = array();
		$objActSheet = $objPHPExcel->getActiveSheet();

		$prop = 0;
		$objActSheet->setCellValue($colArr[$prop].'1', '用户uid');$widArr[$colArr[$prop]] = 10;$prop++;
		$objActSheet->setCellValue($colArr[$prop].'1', '昵称');$widArr[$colArr[$prop]] = 24;$prop++;
		foreach ($activeInfo['leavemess_fields_arr'] as $key => $value) {
			$objActSheet->setCellValue($colArr[$prop].'1', $value['name']);$widArr[$colArr[$prop]] = 12;$prop++;
		}
		$objActSheet->setCellValue($colArr[$prop].'1', '手机归属地');$widArr[$colArr[$prop]] = 12;$prop++;
		$objActSheet->setCellValue($colArr[$prop].'1', '订单号');$widArr[$colArr[$prop]] = 24;$prop++;
		$objActSheet->setCellValue($colArr[$prop].'1', '支付流水号');$widArr[$colArr[$prop]] = 24;$prop++;
		$objActSheet->setCellValue($colArr[$prop].'1', '总额');$widArr[$colArr[$prop]] = 12;$prop++;
		$objActSheet->setCellValue($colArr[$prop].'1', '创建时间');$widArr[$colArr[$prop]] = 20;$prop++;
		$objActSheet->setCellValue($colArr[$prop].'1', '定位地址');$widArr[$colArr[$prop]] = 12;$prop++;
		$objActSheet->setCellValue($colArr[$prop].'1', '定位城市');$widArr[$colArr[$prop]] = 12;$prop++;
		$objActSheet->setCellValue($colArr[$prop].'1', '定位地址');$widArr[$colArr[$prop]] = 12;$prop++;
		$objActSheet->setCellValue($colArr[$prop].'1', '语义描述');$widArr[$colArr[$prop]] = 12;$prop++;
		$objActSheet->setCellValue($colArr[$prop].'1', '核销状态');$widArr[$colArr[$prop]] = 12;$prop++;
		$objActSheet->setCellValue($colArr[$prop].'1', '核销时间');$widArr[$colArr[$prop]] = 18;$prop++;
		$objActSheet->setCellValue($colArr[$prop].'1', '核销备注');$widArr[$colArr[$prop]] = 12;$prop++;
		$totalCol = $prop - 1;

		$i = 2;
		foreach ($signupList as $key => $value) {
			$prop = 0;
			$objActSheet->setCellValue($colArr[$prop++].$i, $value['uid']);
			$objActSheet->setCellValueExplicit($colArr[$prop++].$i, filterEmoji($value['username'])); //过滤微信emoji字符
			foreach ($activeInfo['leavemess_fields_arr'] as $key2 => $value2) {
				if ($value2['flag'] == 'idcard') {
					$objActSheet->setCellValueExplicit($colArr[$prop++].$i, $value[$value2['flag']]);
				} else {
					$objActSheet->setCellValue($colArr[$prop++].$i, $value[$value2['flag']]);
				}
			}
			$objActSheet->setCellValue($colArr[$prop++].$i, $value['mobile_source']);
			$objActSheet->setCellValue($colArr[$prop++].$i, $value['order_no']);
			$objActSheet->setCellValue($colArr[$prop++].$i, $value['payment_trade_no']);
			$objActSheet->setCellValue($colArr[$prop++].$i, $value['total_fee']);
			$objActSheet->setCellValue($colArr[$prop++].$i, $value['create_time_show']);
			$objActSheet->setCellValue($colArr[$prop++].$i, $value['location_address']);
			$objActSheet->setCellValue($colArr[$prop++].$i, $value['location_city']);
			$objActSheet->setCellValue($colArr[$prop++].$i, $value['location_district']);
			$objActSheet->setCellValue($colArr[$prop++].$i, $value['sematic_description']);
			$objActSheet->setCellValue($colArr[$prop++].$i, strip_tags($value['writeoff_status_show']));
			$objActSheet->setCellValue($colArr[$prop++].$i, $value['writeoff_time_show']);
			$objActSheet->setCellValue($colArr[$prop++].$i, $value['writeoff_remark']);
			$i++;
		}

		//设置宽度
		foreach ($widArr as $key => $value) {
			$objActSheet->getColumnDimension($key)->setWidth($value);
		}

		//合并页头并加上背景色
		$objActSheet->getStyle('A1:'.$colArr[$totalCol].'1')->getFill()->setFillType(\PHPExcel_Style_Fill::FILL_SOLID);
		$objActSheet->getStyle('A1:'.$colArr[$totalCol].'1')->getFill()->getStartColor()->setARGB('FBF136');
		
		// Set active sheet index to the first sheet, so Excel opens this as the first sheet

		// Redirect output to a client’s web browser (Excel5)
		header('Content-Type: application/vnd.ms-excel; charset=gb2312;');
		header('Content-Disposition: attachment;filename="'.$filename.'.xls"');
		header('Cache-Control: max-age=0');
		// If you're serving to IE 9, then the following may be needed
		header('Cache-Control: max-age=1');

		// If you're serving to IE over SSL, then the following may be needed
		header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
		header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
		header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
		header ('Pragma: public'); // HTTP/1.0

		$objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
		$objWriter->save('php://output');
		exit;
	}

}